from fastapi import (
    APIRouter,
    BackgroundTasks,
    File,
    Depends,
    Query,
    Request,
    UploadFile,
)
from module_admin.service.common_service import CommonService
from module_admin.service.ocr_config_service import OcrConfigService
from module_admin.service.llm_service import LlmService
from utils.log_util import logger
from utils.response_util import ResponseUtil
from sqlalchemy.ext.asyncio import AsyncSession
from config.get_db import get_db
from module_admin.entity.vo.ocr_config_vo import OcrConfigPageQueryModel
from module_admin.entity.vo.llm_vo import LlmPageQueryModel

commonController = APIRouter(prefix="/common")


@commonController.post("/upload")
async def common_upload(request: Request, file: UploadFile = File(...)):
    upload_result = await CommonService.upload_service(request, file)
    logger.info("上传成功")

    return ResponseUtil.success(model_content=upload_result.result)


@commonController.get("/download")
async def common_download(
    request: Request,
    background_tasks: BackgroundTasks,
    file_name: str = Query(alias="fileName"),
):
    download_result = await CommonService.download_services(
        background_tasks, file_name, False
    )
    logger.info(download_result.message)

    return ResponseUtil.streaming(data=download_result.result)


@commonController.get("/download/resource")
async def common_download_resource(request: Request, resource: str = Query()):
    download_resource_result = await CommonService.download_resource_services(resource)
    logger.info(download_resource_result.message)

    return ResponseUtil.streaming(data=download_resource_result.result)


@commonController.get("/statistical")
async def common_download_resource(
    request: Request, query_db: AsyncSession = Depends(get_db)
):
    ocr_config_list = await OcrConfigService.get_OcrConfig_list_services(
        query_db, OcrConfigPageQueryModel(), is_page=True
    )

    llm_config_list = await LlmService.get_llm_list_services(
        query_db, LlmPageQueryModel(), is_page=True
    )

    return ResponseUtil.success(
        data={"ocr": ocr_config_list.total, "llm": llm_config_list.total}
    )
